/*************************************
* @update: 2022-08-22   LiLinBin  [创建文件]
*
* @description: color-picker颜色选择器 [优化颜色选择器bug]
****************************************/

// 纯色,渐变色都启用
/* <color-picker :pureColor="pureColor"
    :gradientColor="gradientColor"
    @pureColorChange="changeBgColor"
    @gradientColorChange="changeBgColor"
    @activeKeyChange="colorPickerDomShowColor"
    useType="both"
    format="rgb" /> */



export default {
    data: () => ({
        // colorPickerColor: '',    //记录当前颜色
        useColorPicker: false //是否是手动点击使用了
    }),
    watch: {
        /* propsColor(newColor) {
            if (newColor.includes('linear-gradient')) {
				this.pureColor = ''
				this.gradientColor = newColor //渐变色
				this.colorPickerDomShowColor(newColor)
			} else {
				this.pureColor = newColor
				this.gradientColor = ''
			}
        } */
    },
    methods: {
        //colorPicker的 div.current-color 显示当前的颜色
        colorPickerDomShowColor (color) {
            this.colorPickerColor = color || this.colorPickerColor
            if (!this.colorPickerColor) return

            this.$nextTick(() => {
                const colorPicker = this.$el.querySelector('.current-color')
                colorPicker.style.background = this.colorPickerColor
            })
        },


        showColorPicker (e) {
            const picker = document.querySelector('.vc-colorpicker')
            if (!picker) return

            const pickerW = picker.offsetWidth
            const pickerH = picker.offsetHeight

            const { clientWidth, clientHeight } = document.body

            const left = Math.min(
                e.clientX + (e.target.offsetWidth - e.offsetX),
                clientWidth - pickerW
            )
            const top = Math.min(
                e.clientY + (e.target.offsetHeight - e.offsetY) + 2,
                clientHeight - pickerH
            )

            const pickerParent = picker.parentElement
            pickerParent.style.cssText += `left:${left}px;top:${top}px;transform:unset;`

            this.useColorPicker = true //手动点击了
            // if (!this.colorPickerColor) return
            this.colorPickerDomShowColor()
            this.observeColorPickerShowHide(pickerParent)
        },


        //监听color-picker的显示和隐藏
        observeColorPickerShowHide (targetNode) {
            const callback = (mutationsList, observer) => {
                this.useColorPicker = false
                this.colorPickerDomShowColor()
                observer.disconnect()
                observer = null
            }
            const config = { attributes: true }
            const observer = new MutationObserver(callback)
            observer.observe(targetNode, config)
        },


        /* changeBgColor (newColor) {
            if (!this.useColorPicker) return
            if (newColor == this.colorPickerColor) return

            //改变颜色后的相关操作
        } */
    },
    beforeUnmount () { }
}